<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2022-12-21 17:10:12
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\See.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { PropType, reactive, ref, unref } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'

import { useTable } from '@/hooks/web/useTableTest'
// import { zcMarkOrderDetailedListApi } from '@/api/cy/xMarking'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
import { Folder } from '@element-plus/icons-vue'
import { dbMarkOrderSeeApi, dbMarkOrderSeeexportApi } from '@/api/forms'
/****************************** 变量 start ******************************/
const dict: any = wsCache.get('dict')

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})
/****************************** 组件参数 end ******************************/
const searchRef = ref() // 搜索的标签
const breedSubData = ref([]) // 品种的枚举
const dictRelsData = ref() // 联动数据

/****************************** 函数方法 start ******************************/
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}
/****************************** 函数方法 end ******************************/
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: dbMarkOrderSeeApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'enclosure_name',
    label: '栏位名称',
    width: 150,
    search: {
      show: true
    }
  },
  // {
  //   field: 'customer_name',
  //   label: '牧场名称',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'asset_code',
    label: '资产编码(注射)',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '资产编码(项圈)',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: false
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: false
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.animal_sex
      },
      show: false
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'purpose',
    label: '用途',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.purpose
      },
      show: false
    }
  }
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 170,
  //   form: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       disabled: true,
  //       type: 'datetime',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   },
  //   search: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       'is-range': true,
  //       'unlink-panels': true,
  //       rangeSeparator: 'To',
  //       type: 'daterange',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   }
  // },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作',
  //   form: {
  //     show: false
  //   },
  //   detail: {
  //     show: false
  //   }
  // }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 初始化 start ******************************/
const newFixedSearch = ref({})
let mark_state = ref('')
const init = async () => {
  // 调用查看接口查询数据
  // await getMedicalOrderSee()
  newFixedSearch.value = {
    id: props.currentRow.id
  }
  tableObject.fixedSearch = newFixedSearch.value
  getList()
  mark_state.value = getDictLabel('mark_state', props.currentRow.state)
  console.log(tableObject)
}
init()

const exportClick = async () => {
  dialogTableVisible.value = true
  // let aaa: any = tableObject.paramsObj.params
  // console.log(aaa, tableObject.count)
  let res: any = await dbMarkOrderSeeApi({
    id: props.currentRow.id
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    // console.log(res)
    FormsNumber.value = Math.ceil(res.count / 10000)
  }
}

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)

const Export = async (index) => {
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa, index)
  let { data }: any = await dbMarkOrderSeeexportApi({
    request: {
      id: props.currentRow.id,
      pageNo: index,
      pageSize: '10000'
    },
    layout_data: {
      file_name: '打标单详情',
      column_cell_start: 'A5',
      column_value: 'detailed',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '栏位名称',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'enclosure_name'
        },
        {
          title: '资产编码（注射）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code'
        },
        {
          title: '资产编码（项圈）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code_2'
        },
        {
          title: '耳标',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'earcon_code'
        },
        {
          title: '畜别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'breed',
          give_type: 'variable',
          give_value: 'breed'
        },
        {
          title: '品种',
          width: 15,
          cell_type: 'dict',
          dict_type: 'breed_sub',
          give_type: 'variable',
          give_value: 'breed_sub'
        },
        {
          title: '性别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'animal_sex',
          give_type: 'variable',
          give_value: 'sex'
        },
        {
          title: '用途',
          width: 10,
          cell_type: 'dict',
          dict_type: 'purpose',
          give_type: 'variable',
          give_value: 'purpose'
        },
        {
          title: '打标日期',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'create_time'
        },
        {
          title: '活畜月龄（月）',
          width: 15,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'month_age'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:K1',
          give_type: 'format',
          give_value: '${code}打标单详情',
          horizontal: 'center',
          border: true,
          size: '16'
        },
        {
          cell_type: 'string',
          cell: 'A2:D2',
          give_type: 'format',
          give_value: '牧场名称：${pasture_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E2:G2',
          give_type: 'format',
          give_value: '单号：${code}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell: 'H2:J2',
          cell_type: 'string',
          give_type: 'format',
          give_value: '打标申请日期：${create_time}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'K2:K2',
          give_type: 'format',
          give_value: '状态：${dict.mark_state.${state}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A3:D3',
          give_type: 'format',
          give_value: '牧场地址：${pasture_address}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E3:G3',
          give_type: 'format',
          give_value: '打标申请数量：${number}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'H3:K3',
          give_type: 'format',
          give_value: '打标完成数量：${marked_number}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A4:D4',
          give_type: 'format',
          give_value: '创建人：${create_user_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E4:K4',
          give_type: 'format',
          give_value: '创建时间：${create_time}',
          horizontal: 'left',
          border: true,
          size: '12'
        }
      ],
      dict: ['mark_state']
    }
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)

    console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}
/****************************** 初始化 end ******************************/
</script>

<template>
  <div>
    <el-button
      style="margin-bottom: 20px"
      @click="exportClick"
      type="primary"
      size="small"
      :icon="Folder"
      >导出</el-button
    >

    <ContentWrap title="主数据">
      <Descriptions :schema="props.detailSchema" :data="props.currentRow || {}">
        <template #breed="{ row }: { row: any }">
          <div>{{ getDictLabel('breed', row.breed) }}</div>
        </template>
        <template #breed_sub="{ row }: { row: any }">
          <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
        </template>
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('mark_state', row.state) }}</div>
        </template>
        <template #purpose="{ row }: { row: any }">
          <div>{{ getDictLabel('purpose', row.purpose) }}</div>
        </template>
      </Descriptions>
    </ContentWrap>

    <ContentWrap title="明细数据">
      <Table
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList.detailed"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        @register="register"
        :selection="false"
      />
    </ContentWrap>
  </div>
  <el-dialog v-model="dialogTableVisible" title="打标主档导出详情">
    <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
      <span style="margin: 20px">打标主档 - {{ item }}</span>
      <ElButton type="primary" @click="Export(item)">导出</ElButton>
    </div>
  </el-dialog>
</template>
